package com.haoze.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public final class ExcelUtil {

    //值域、字典删除下拉值导出Excel
    private static final List<String> EXCEL_HEADER = Arrays.asList("引用源", "名称", "具体位置");
    private static final String[] EXCEL_HEADER_COL = {"source", "detailSourceName","position"};

    public static byte[] exportExcel(List<Map<String, String>> columns) {
        List<List<String>> result = new ArrayList<>();
        result.add(EXCEL_HEADER);
        for (Map<String, String> col : columns) {
            List<String> column = new ArrayList<>();
            for (int i = 0; i < EXCEL_HEADER_COL.length; i++) {
                String colName = EXCEL_HEADER_COL[i];
                String defaultValue = "";
                column.add(col.getOrDefault(colName, defaultValue));
            }
            result.add(column);
        }
        try {
            return asExcellFile(result);
        } catch (IOException e) {
            throw new RuntimeException("Could not wirte Excel as byte array!!", e);
        }
    }

    private static byte[] asExcellFile(List<List<String>> result) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("导出Excel");
        for (int y = 0; y < result.size(); y++) {
            List<String> col = result.get(y);
            XSSFRow row = sheet.createRow(y);
            for (int x = 0; x < col.size(); x++) {
                XSSFCell cell = row.createCell(x);
                cell.setCellValue(StringUtils.isBlank(col.get(x)) ? "" : col.get(x));
            }
        }
        byte[] res;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            workbook.write(out);
            out.flush();
            res = out.toByteArray();
        }
        return res;
    }

    public static ResponseEntity<byte[]> getExcelHttpResponseEntity(String filename, byte[] body) {
        ResponseEntity.BodyBuilder res = ResponseEntity.status(HttpStatus.OK);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/vnd.ms-excel");
        headers.set("Content-Disposition", "attachment;filename=" + filename);
        return res.headers(headers).body(body);
    }
}
